﻿using Demo.Api.Config;
using Demo.Api.Controllers.Commin;
using Demo.Interface;
using Demo.Model.Dto.Goods;
using Demo.Model.Other;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
using static Demo.Model.Other.UploadDemo;

namespace Demo.Api.Controllers.BasicData
{
    /// <summary>
    /// 商品
    /// </summary>
    //[Route("api/[controller]")]
    //[ApiController]
    //[Authorize]
    public class GoodsController : WebApiBaseController
    {
        private readonly IGoodsService _goodsService;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private SortedDictionary<string, object> _data;
        public GoodsController(IGoodsService goodsService, IWebHostEnvironment webHost)
        {
            _goodsService = goodsService;
            _webHostEnvironment = webHost;
        }
        /// <summary>
        /// 查询商品
        /// </summary>
        /// <param name="goodsWhere"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResultLayui> GetListGoods(GoodsWhere goodsWhere)
        {
            var res = Task.Run(async () =>
            {
                var data = await _goodsService.GetListGoods(goodsWhere);
                return ResultHelper.Successlayui(data.Item3, data.Item2, "");
            });
            return await res;
        }
        /// <summary>
        /// 查询商品实体
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetGoods(int id)
        {
            var res = Task.Run(async () =>
            {
                var data = await _goodsService.GetGoods(id);
                return ResultHelper.Success(data.Item3, data.Item2);
            });
            return await res;
        }

        /// <summary>
        /// 新增商品
        /// </summary>
        /// <param name="goodsAdd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GoodsAdd(GoodsAdd goodsAdd)
        {
            var res = Task.Run(async () =>
            {
                if (string.IsNullOrEmpty(goodsAdd.Goods_Name))
                {
                    return ResultHelper.Error("参数不能为空");
                }
                var data = await _goodsService.GoodsAdd(goodsAdd);
                return ResultHelper.Success(data.Item3, data.Item2);
            });
            return await res;
        }
        /// <summary>
        /// 修改商品
        /// </summary>
        /// <param name="goodsEdit"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GoodsEdit(GoodsEdit goodsEdit)
        {
            var res = Task.Run(async () =>
            {
                if (string.IsNullOrEmpty(goodsEdit.Goods_Name))
                {
                    return ResultHelper.Error("参数不能为空");
                }
                var data = await _goodsService.GoodsEdit(goodsEdit);
                return ResultHelper.Success(data.Item1, data.Item2);
            });
            return await res;
        }
        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GoodsDel(int id)
        {
            var res = Task.Run(async () =>
            {
                if (string.IsNullOrEmpty(id.ToString()))
                {
                    return ResultHelper.Error("参数不能为空");
                }
                var data = await _goodsService.GoodsDel(id);
                return ResultHelper.Success(data.Item1, data.Item2);
            });
            return await res;
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> FileSave(IFormFile file, int id, int xh)
        {
            string fileName = "";
            var saveName = "";
            var filePath = "";
            try
            {
                //获取Form提交的文件
                if (file != null)
                {
                    if (file.Length > 0)
                    {
                        var now = DateTime.Now;
                        //文件存储路径
                        filePath = string.Format("wwwroot/Uploads/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
                        //获取当前web目录
                        var webRootPath = _webHostEnvironment.ContentRootPath;
                        //保存目录不存在就创建这个目录
                        if (!Directory.Exists(webRootPath + filePath))
                        {
                            Directory.CreateDirectory(webRootPath + filePath);
                        }
                        #region  图片文件的条件判断
                        //文件后缀
                        var fileExtension = Path.GetExtension(file.FileName);

                        //判断后缀是否是图片
                        const string fileFilt = ".gif|.jpg|.jpeg|.png|.bmp";
                        if (fileExtension == null)
                        {
                            return ResultHelper.Error("上传的文件没有后缀");
                        }
                        if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                        {
                            return ResultHelper.Error("请上传jpg、png、gif、bmp格式的图片");
                        }

                        //判断文件大小    
                        long length = file.Length;
                        if (length > 1024 * 1024 * 4) //4M
                        {
                            return ResultHelper.Error("上传的文件不能大于2M");
                        }

                        #endregion
                        var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                        var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                        saveName = strDateTime + strRan + fileExtension;
                        //在指定目录创建文件
                        fileName = webRootPath + filePath + saveName;//文件名
                        FileHelper.CreateFile(fileName);

                        using (var stream = new FileStream(webRootPath + filePath + saveName, FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                        }
                    }
                }
                var webpath = _webHostEnvironment.ContentRootPath;
                GoodsImgPuth imgPuths = new GoodsImgPuth();
                imgPuths.Xh = xh;
                imgPuths.Id = id;
                imgPuths.ImgPath = filePath + saveName;
                imgPuths.DelImgPath = webpath + "/wwwroot";
                await _goodsService.Imgputh(imgPuths);
                return ResultHelper.Success(filePath.Remove(0, 7) + saveName, "上传成功");
            }
            catch (Exception ex)
            {
                return ResultHelper.Error("上传失败" + ex.GetBaseException());
            }
        }
        /// <summary>
        /// 上传图片,通过Form表单提交 上传多个
        /// </summary>
        /// <returns></returns>
        [Route("Upload/FormImg")]
        [HttpPost]
        public async Task<ApiResult> UploadImg(List<IFormFile> files)
        {
            if (files.Count < 1)
            {
                return ResultHelper.Error("文件为空");
            }
            //返回的文件地址
            List<string> filenames = new List<string>();
            var now = DateTime.Now;
            //文件存储路径
            var filePath = string.Format("/Uploads/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("yyyyMM"), now.ToString("yyyyMMdd"));
            //获取当前web目录
            var webRootPath = _webHostEnvironment.WebRootPath;
            if (!Directory.Exists(webRootPath + filePath))
            {
                Directory.CreateDirectory(webRootPath + filePath);
            }
            try
            {
                for (int i = 0; i < files.Count; i++)
                {

                    #region  图片文件的条件判断
                    //文件后缀
                    var fileExtension = Path.GetExtension(files[i].FileName);

                    //判断后缀是否是图片
                    const string fileFilt = ".gif|.jpg|.jpeg|.png|.bmp";
                    if (fileExtension == null)
                    {
                        break;
                        //return Error("上传的文件没有后缀");
                    }
                    if (fileFilt.IndexOf(fileExtension.ToLower(), StringComparison.Ordinal) <= -1)
                    {
                        break;
                        //return Error("请上传jpg、png、gif格式的图片");
                    }

                    //判断文件大小    
                    long length = files[i].Length;
                    if (length > 1024 * 1024 * 2) //2M
                    {
                        break;
                        //return Error("上传的文件不能大于2M");
                    }

                    #endregion

                    var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                    var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                    var saveName = strDateTime + strRan + fileExtension;

                    //插入图片数据                 
                    using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
                    {
                        await files[i].CopyToAsync(fs);
                        fs.Flush();
                    }

                    filenames.Add(filePath + saveName);

                }

                return ResultHelper.Success(filenames, "");
            }
            catch (Exception ex)
            {
                //这边增加日志，记录错误的原因
                //ex.ToString();
                return ResultHelper.Error("上传失败" + ex.GetBaseException());
            }
        }

    }
}
